﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace Liebrand.UrlShortener
{
    public sealed class UrlShortenerHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
        }


        #endregion

        #region Methods

        void context_BeginRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;

            var path = context.Request.Url.AbsolutePath;
            if (path.Length > 1)
            {
                var id = path.Substring(1, path.Length - 1);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    var adminApp = SPAdministrationWebApplication.Local;

                    using (SPSite site = adminApp.Sites[0])
                    {
                        using (SPWeb web = site.RootWeb)
                        {

                            var list = web.Lists[SPUtility.GetLocalizedString("$Resources:liebrandurlshortener,StorageName", "liebrandurlshortener", web.Language)];

                            var urlQuery = new SPQuery();
                            urlQuery.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + id + "</Value></Eq></Where>";

                            var items = list.GetItems(urlQuery);
                            if (items.Count == 1)
                            {
                                var item = items[0];
                                context.Response.Redirect(item["RedirectTo"].ToString());
                            }
                        }
                    }

                });
            }
        }
        #endregion
    }
}
